//
//  WaitingShow.m
//  WaitingShow-Demo
//
//  Created by telen on 12-11-1.
//  Copyright (c) 2012年 刘赞黄Telen. All rights reserved.
//

#import "WaitingShow.h"
#import "AppDelegate.h"
#import "Lyt.h"

@implementation CoverView
@synthesize deletegate = _deletegate;

-(void)removeFromSuperview{
    if ([_deletegate respondsToSelector:@selector(CoverViewDidRemovedFromSuperView)]) {
        [_deletegate CoverViewDidRemovedFromSuperView];
    }
    [super removeFromSuperview];
}

@end


static WaitingShow * _shareSingleShow = nil;

@implementation WaitingShow

@synthesize imageSize = _imageSize;
@synthesize centerOffset = _centerOffset;
@synthesize image = _image;
@synthesize textFont = _textFont;
@synthesize touchScreenHide = _touchScreenHide;
@synthesize notToSaveAttr = _notToSaveAttr;
@synthesize queueArr = _queueArr;

// 获取单例
+ (WaitingShow*)shareSingleShow{
    if (_shareSingleShow != nil) {
        return _shareSingleShow;
    }
    [self alloc];
    return _shareSingleShow;
}

- (void)setDefaultWindow:(UIView *)v
{
    defaultWindow = v;
}

+ (id)alloc{
    if (_shareSingleShow != nil)
        return nil;
    @synchronized(self){
        _shareSingleShow = [[super alloc] init];
        return nil;
    }
    return nil;
}

+ (id)createInstance
{
    return [[[super alloc] init] autorelease];
}

//隐藏Show
- (void)hideShow{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(hideShow) withObject:nil waitUntilDone:NO];
        return;
    }
    [self doHideView];
}
- (void)hideShowRightNow{
    [self hideView];
}
- (void)hideShowWithIntervalTime:(CGFloat)intervaltime{
    [_hideTimer invalidate],_hideTimer = nil;
    _hideTimer = [NSTimer timerWithTimeInterval:intervaltime target:self selector:@selector(hideShow) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:_hideTimer forMode:NSRunLoopCommonModes];
}

//显示纯文本，支持\n换行 并显示等待动画
//window上
- (void)showWaitingString:(NSString*)str{
    if (defaultWindow) {
        [self showWaitingString:str inSuperView:defaultWindow];
    }else{
        AppDelegate* appdelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [self showWaitingString:str inSuperView:appdelegate.window];
    }
}
//指定superView
- (void)showWaitingString:(NSString*)str inSuperView:(UIView*)superView{
    //
    UIFont * font;
    if (self.textFont)
        font = self.textFont;
    else
        font = [UIFont systemFontOfSize:SizeOfFont];
    CGPoint point = self.centerOffset;
    //
    UIActivityIndicatorView * aiview = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, TopImageWidth, TopImageHeight)];
    aiview.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [aiview startAnimating];
    [self showString:str withSuperView:superView atCenterPointOffset:point withFont:font withIntervalTime:0.f withTopView:aiview];
    [aiview release];
}

//显示纯文本，支持\n换行 等待几秒消失
//window上
- (void)showString:(NSString*)str andAutoHide:(BOOL)yesOrNo{
    if (yesOrNo)
        [self showString:str withIntervalTime:WaitShowIntervalTime];
    else
        [self showString:str withIntervalTime:0.f];
}
- (void)showString:(NSString*)str withIntervalTime:(CGFloat)intervaltime{
    NSAssert(str != nil, @"waitingshow 显示的文字不能为空！");
    if (defaultWindow) {
        [self showString:str inSuperView:defaultWindow withIntervalTime:intervaltime];
    }else{
        AppDelegate* appdelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [self showString:str inSuperView:appdelegate.window withIntervalTime:intervaltime];
    }
}

//指定superView
- (void)showString:(NSString*)str inSuperView:(UIView*)superView andAutoHide:(BOOL)yesOrNo{
    if (yesOrNo)
        [self showString:str inSuperView:superView withIntervalTime:WaitShowIntervalTime];
    else
        [self showString:str inSuperView:superView withIntervalTime:0.f];
}
- (void)showString:(NSString*)str inSuperView:(UIView*)superView withIntervalTime:(CGFloat)intervaltime{
    //
    UIFont * font;
    if (self.textFont)
        font = self.textFont;
    else
        font = [UIFont systemFontOfSize:SizeOfFont];
    CGPoint point = self.centerOffset;
    //
    UIImageView * topSubView = nil;
    if (self.image) {
        CGRect rect = CGRectMake(0, 0, TopImageWidth, TopImageHeight);
        if (self.imageSize.width != 0 && self.imageSize.height != 0)
            rect.size = self.imageSize;
        topSubView = [[UIImageView alloc] initWithFrame:rect];
        topSubView.image = self.image;
        [self showString:str withSuperView:superView atCenterPointOffset:point withFont:font withIntervalTime:intervaltime withTopView:topSubView];
        [topSubView release];
    }else{
        [self showString:str withSuperView:superView atCenterPointOffset:point withFont:font withIntervalTime:intervaltime withTopView:topSubView];
    }
}

//动态修改图片及文字
- (void)changeShowingSting:(NSString*)str withAnimation:(BOOL)yesOrNo{
    if (_view == nil) return;
    _txtlabel.text = str;
    if (yesOrNo) 
        [self doShowView:_txtlabel];
}
- (void)changeShowingImage:(UIImage*)image withAnimation:(BOOL)yesOrNo{
    if (_view == nil) return;
    self.image = image;
    [_topSubView removeFromSuperview],_topSubView = nil;
    //
    CGRect rect = CGRectMake(0, 0, TopImageWidth, TopImageHeight);
    if (self.imageSize.width != 0 && self.imageSize.height != 0)
        rect.size = self.imageSize;
    UIImageView * topSubView = [[UIImageView alloc] initWithFrame:rect];
    topSubView.image = self.image;
    [self addTopSubView:topSubView];
    [topSubView release];
    //
    if (yesOrNo)
        [self doShowView:_topSubView];
}

//录音等待框
- (void)showSoundRecordingString:(NSString*)str inSuperView:(UIView*)superView{
    self.imageSize = CGSizeMake(72, 72);
    self.notToSaveAttr = YES;
    self.image = [UIImage imageNamed:@"WaitingShow-sound recording"];
    self.toQueueArr = NO;
    [self showString:str inSuperView:superView andAutoHide:NO];
}

//显示图片对错
//window上
- (void)showSuccessString:(NSString*)str autoHideTime:(CGFloat)intervaltime{
    self.imageSize = CGSizeMake(65, 50);
    self.notToSaveAttr = YES;
    self.image = [UIImage imageNamed:@"WaitingShow-duigou.png"];
    [self showString:str withIntervalTime:intervaltime];
}
- (void)showFailString:(NSString*)str autoHideTime:(CGFloat)intervaltime{
    self.imageSize = CGSizeMake(65, 50);
    self.notToSaveAttr = YES;
    self.image = [UIImage imageNamed:@"WaitingShow-cuowu.png"];
    [self showString:str withIntervalTime:intervaltime];
}
//指定superView
- (void)showSuccessString:(NSString*)str inSuperView:(UIView*)superView autoHideTime:(CGFloat)intervaltime{
    self.imageSize = CGSizeMake(65, 50);
    self.notToSaveAttr = YES;
    self.image = [UIImage imageNamed:@"WaitingShow-duigou.png"];
    [self showString:str inSuperView:superView withIntervalTime:intervaltime];
}
- (void)showFailString:(NSString*)str inSuperView:(UIView*)superView autoHideTime:(CGFloat)intervaltime{
    self.imageSize = CGSizeMake(65, 50);
    self.notToSaveAttr = YES;
    self.image = [UIImage imageNamed:@"WaitingShow-cuowu.png"];
    [self showString:str inSuperView:superView withIntervalTime:intervaltime];
}

//等待后，对错提醒
-(void)didFinshWaitingShowSuccessString:(NSString*)str autoHideTime:(CGFloat)intervaltime{
    self.imageSize = CGSizeMake(65, 50);
    self.notToSaveAttr = YES;
    [self changeShowingImage:[UIImage imageNamed:@"WaitingShow-duigou.png"] withAnimation:YES];
    [self changeShowingSting:str withAnimation:YES];
    [self hideShowWithIntervalTime:intervaltime];
}
-(void)didFinshWaitingShowFailString:(NSString*)str autoHideTime:(CGFloat)intervaltime{
    self.imageSize = CGSizeMake(65, 50);
    self.notToSaveAttr = YES;
    [self changeShowingImage:[UIImage imageNamed:@"WaitingShow-cuowu.png"] withAnimation:YES];
    [self changeShowingSting:str withAnimation:YES];
    [self hideShowWithIntervalTime:intervaltime];
}

//自带图片show
- (void)showImageWithName:(NSString*)name withString:(NSString*)str autoHideTime:(CGFloat)intervaltime
{
    self.imageSize = CGSizeMake(65, 65);
    self.notToSaveAttr = YES;
    self.image = [UIImage imageNamed:name];
    [self showString:str withIntervalTime:intervaltime];
}

//--------------------------------

-(id)init{
    if (self = [super init]) {
        self.centerOffset = CGPointMake(0, 0);
        self.imageSize = CGSizeMake(0, 0);
        self.notToSaveAttr = YES;
        self.touchScreenHide = NO;
        self.toQueueArr = YES;
        self.queueArr = [NSMutableArray arrayWithCapacity:0];
        self.removalDuplication = YES;
    }
    return self;
}

-(void)dealloc{
    [self hideView];
    self.queueArr = nil;
    self.textFont = nil;
    self.image = nil;
    [super dealloc];
}

#pragma mark- private Menthods // 私有方法

-(void)showOnMainThread:(NSDictionary*)dict{
    //主线程判断
    if (![NSThread currentThread].isMainThread) {
        [self performSelectorOnMainThread:@selector(showOnMainThread:) withObject:dict waitUntilDone:NO];
        return;
    }
    //数据准备
    NSString * str = [dict objectForKey:@"str"];
    UIView * superView = [dict objectForKey:@"superView"];
    CGPoint point = [((NSValue*)[dict objectForKey:@"centerPoint"]) CGPointValue];
    UIFont * font = [dict objectForKey:@"font"];
    CGFloat intervaltime = [[dict objectForKey:@"intervalTime"] floatValue];
    UIView * topSubView = [dict objectForKey:@"topSubView"];
    
//    //添加背景view覆盖
//    if (!superView) {
//        [PublicMethod showNetAlert];
//        
//        return;
//    }
    [self addViewToSuperView:superView];
    
    //尺寸处理
    CGSize maxStrSize = CGSizeMake(TopStrWidth, TopSrtHeight);
    CGSize vsize = ( topSubView ? topSubView.bounds.size : CGSizeMake(0, 0));
    //CGSize size = [str sizeWithFont:font constrainedToSize:maxStrSize lineBreakMode:0];
    
    NSDictionary *attributes = @{NSFontAttributeName: font};
    CGRect rectSize = [str boundingRectWithSize:maxStrSize
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:attributes
                                              context:nil];
    CGSize size = rectSize.size;
    size.width = (size.width >= vsize.width ? size.width : vsize.width);
    CGRect rect = CGRectMake(Pad, Pad+vsize.height, 0, 0);
    if (topSubView){
        if (size.width < size.height + vsize.height)
            size.width = size.height + vsize.height;
        rect.origin.y += Pad/3.f;
    }
    rect.size = size;
    size.height += (Pad*2+vsize.height);
    size.width += Pad*2;
//    位置处理
    if (point.x == 0 && point.y == 0){
        CGFloat sqrt_wh = (superView.bounds.size.width+superView.bounds.size.height)*0.5;
        point = CGPointMake(sqrt_wh*centerOffsetMultiplyWidth, sqrt_wh*centerOffsetMultiplyHeight);
    }

    //添加提醒框
    [self addCaseWithSize:size atPoint:point];
    
    //添加头部图片view
    if (topSubView)
        [self addTopSubView:topSubView];
    //添加显示文字
    [self addShowString:str inRect:rect withFont:font];
    
    //动画显示View
    [self doShowView:_view];
    
    //设置隐藏
    if (intervaltime > 0)
        [self hideViewInTime:intervaltime];
    
    //isShowing
    _isShowing = YES;
}

-(void)showString:(NSString *)str withSuperView:(UIView*)superView atCenterPointOffset:(CGPoint)point withFont:(UIFont *)font withIntervalTime:(CGFloat)intervaltime withTopView:(UIView*)topSubView{
    if (!str || !superView) {
        NSLog(@"WaittingShow Error: superView:%@ msg:%@",superView,str);
        return;
    }
    //
    NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:str,@"str",superView,@"superView",[NSValue valueWithCGPoint:point],@"centerPoint",font,@"font",[NSNumber numberWithFloat:intervaltime],@"intervalTime",topSubView,@"topSubView", nil];
    if (_view != nil){
        if (self.toQueueArr == NO) {
            [self.queueArr insertObject:dict atIndex:0];
            [self hideView];
        }else{
            BOOL noDupliaction = YES;
            if (self.removalDuplication) {
                NSString* strr = nil;
                for (NSDictionary* dict in self.queueArr) {
                    strr = dict[@"str"];
                    if ([strr isEqualToString:str]) {
                        noDupliaction = NO;
                        break;
                    }
                }
            }
            if(noDupliaction)[self.queueArr addObject:dict];
        }
        //NSLog(@" --Telen--Class\\ %@ --M\\ %@",NSStringFromClass([self class]),NSStringFromSelector(_cmd));
        return;
    }
    [self showOnMainThread:dict];
}

// 显示主View
- (void) addViewToSuperView:(UIView*)superView{
    CGRect rect = superView.bounds;
    _view = [[CoverView alloc] initWithFrame:rect];
    _view.deletegate = self;
    _view.backgroundColor = [UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:0.001f];
    if (!superView) {
        CGSize size=[[UIScreen mainScreen] applicationFrame].size;
        _view.center=CGPointMake(size.width*.5, size.height*.33);
        superView = defaultWindow;
    }
    [superView addSubview:_view];
//    NSLog(@"_view count: %d",_view.retainCount);
    [_view release];
    //
    [_view setUserInteractionEnabled:NO];
    if (self.touchScreenHide) {
        [_view setUserInteractionEnabled:YES];
    }
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didtaped:)];
    [_view addGestureRecognizer:tap];
    [tap release];
    //
    _view.translatesAutoresizingMaskIntoConstraints = NO;
    [_view lyt_alignToParent];
}

// 显示渐变效果
- (void) doShowView:(UIView*)view{
    if (view == nil) return;
    [view setAlpha:0.01f];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.3f];
    [view setAlpha:1.0f];
    [UIView commitAnimations];
}

// 隐藏
- (void) hideView{
    //
    [_hideTimer invalidate],_hideTimer = nil;
    //
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(hideView) withObject:nil waitUntilDone:NO];
        return;
    }
    [_view removeFromSuperview];
}

// 代理函数
- (void)CoverViewDidRemovedFromSuperView{
    if (self.notToSaveAttr) {
        self.centerOffset = CGPointMake(0, 0);
        self.imageSize = CGSizeMake(0, 0);
        self.textFont = nil;
        self.image = nil;
        self.touchScreenHide = NO;
        self.notToSaveAttr = YES;
        self.toQueueArr = YES;
        self.removalDuplication = YES;
    }
    _topSubView = nil;
    _txtlabel = nil;
    _caseView = nil;
    _view = nil;
    //
    if (self.queueArr.count) {
        [self showOnMainThread:[self.queueArr objectAtIndex:0]];
        [self.queueArr removeObjectAtIndex:0];
    }else{
        _isShowing = NO;
    }
//    //NSLog(@" --Telen--Class\\ %@ --M\\ %@",NSStringFromClass([self class]),NSStringFromSelector(_cmd));
}

// 隐藏渐变效果
- (void) doHideView{
    //
    [_hideTimer invalidate],_hideTimer = nil;
    //
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(doHideView) withObject:nil waitUntilDone:NO];
        return;
    }
    //
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:HideAnimationTime];
    [_view setAlpha:0.0f];
    [UIView commitAnimations];
    //
    _hideTimer = [NSTimer timerWithTimeInterval:HideAnimationTime target:self selector:@selector(hideView) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:_hideTimer forMode:NSRunLoopCommonModes];
}

// 添加图片view
- (void) addTopSubView:(UIView*)topSubView{
    CGRect rect = topSubView.frame;
    rect.origin = CGPointMake((_caseView.frame.size.width-topSubView.frame.size.width)/2.f, Pad-0.1f);
    topSubView.frame = rect;
    _topSubView = topSubView;
    [_caseView addSubview:topSubView];
    //防止动画干预再次修正位置
    rect.origin = CGPointMake((_caseView.frame.size.width-topSubView.frame.size.width)/2.f, Pad);
    topSubView.frame = rect;
}

// 添加提醒框
- (void) addCaseWithSize:(CGSize)size atPoint:(CGPoint)pt{
    CGRect rect = CGRectMake(pt.x - size.width/2.f, pt.y - size.height/2.f, size.width, size.height);
    _caseView = [[UIView alloc] initWithFrame:rect];
    [_view addSubview: _caseView];
    [_caseView release];
    //
    UIImage * caseImage = [self imageFromRoundRectanglewidth:size.width height:size.height color:[UIColor colorWithRed:0.f green:0.f blue:0.f alpha:Alpha]];
    _caseView.backgroundColor = [UIColor colorWithPatternImage:caseImage];
    //
    _caseView.translatesAutoresizingMaskIntoConstraints = NO;
    if (_delegate && [_delegate respondsToSelector:@selector(WaitingShow_AutoLayoutCaseView:withWeihtHeight:)]) {
        [_delegate WaitingShow_AutoLayoutCaseView:_caseView withWeihtHeight:size];
    }else{
        [_caseView lyt_centerXInParentWithOffset:pt.x];
        [_caseView lyt_centerYInParentWithOffset:pt.y];
        [_caseView lyt_setSize:size];
    }
}

// 自动隐藏提醒框方法
-(void)hideViewInTime:(CGFloat)intervaltime{
    [_hideTimer invalidate],_hideTimer = nil;
    _hideTimer = [NSTimer timerWithTimeInterval:intervaltime target:self selector:@selector(doHideView) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_hideTimer forMode:NSRunLoopCommonModes];
}

// 添加显示文字
-(void)addShowString:(NSString*)str inRect:(CGRect)rect withFont:(UIFont*)font{
    UILabel * txtlabel = [[UILabel alloc] initWithFrame:rect];
    txtlabel.backgroundColor = [UIColor clearColor];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
    [txtlabel setTextAlignment:NSTextAlignmentCenter];
#else
    [txtlabel setTextAlignment:UITextAlignmentCenter];
#endif
    txtlabel.font = font;
    txtlabel.textColor = [UIColor whiteColor];
    txtlabel.text = str;
    txtlabel.numberOfLines = 0;
    _txtlabel = txtlabel;
    [_caseView addSubview:txtlabel];
    [txtlabel release];
}

// 点击手势事件方法
-(void)didtaped:(UIGestureRecognizer*)tap{
//    //NSLog(@" --Telen--Class\\ %@ --M\\ %@",NSStringFromClass([self class]),NSStringFromSelector(_cmd));
//    if (self.touchScreenHide == YES)
        [self doHideView];
}

// 绘制CaseImage
-(UIImage *)imageFromRoundRectanglewidth:(float)width height:(float)height color:(UIColor *)color
{
    if (Radius > width/2.f || Radius > height/2.f)
        return nil;
    // set the size
    CGSize size  = CGSizeMake(width, height);
    // check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
//    if (UIGraphicsBeginImageContextWithOptions != NULL)
        UIGraphicsBeginImageContextWithOptions(size,NO,0.0);// 开启图片域
//    else
//        // iOS is < 4.0
//        UIGraphicsBeginImageContext(size);
    
    CGContextRef ref = UIGraphicsGetCurrentContext();// 建立上小文
    CGContextSetFillColorWithColor(ref, color.CGColor);//设置填充色
    CGContextSetStrokeColorWithColor(ref, color.CGColor);//设置线条颜色
    CGContextMoveToPoint(ref, Radius, 0);
    CGContextAddArc(ref, Radius, Radius, Radius, -90*M_PI/180, 180*M_PI/180, 1);
    CGContextAddLineToPoint(ref, 0, height-Radius);
    CGContextAddArc(ref, Radius, height-Radius, Radius, 180*M_PI/180, 90*M_PI/180, 1);
    CGContextAddLineToPoint(ref, width-Radius, height);
    CGContextAddArc(ref, width-Radius, height-Radius, Radius, 90*M_PI/180, 0*M_PI/180, 1);
    CGContextAddLineToPoint(ref, width, Radius);
    CGContextAddArc(ref, width-Radius, Radius, Radius, 0*M_PI/180, -90*M_PI/180, 1);
    CGContextClosePath(ref);
    CGContextFillPath(ref);
    CGContextStrokePath(ref);//绘制
    // transfer image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    [image retain];
    UIGraphicsEndImageContext();
    
    return [image autorelease];
}

@end


@implementation UIAlertView (MSG_WaittingShow)

+ (void)showAluertMessage:(NSString *)msg title:(NSString*)title sureBtn:(NSString*)btn
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:btn otherButtonTitles: nil];
    [alert show];
    [alert release];
}

@end
